import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import store from "@/store";

// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};

Vue.use(VueRouter);

const routes = [
  // 重定向
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: Home,
  },
  {
    path: "/goods",
    name: "goods",
    component: () =>
      import(/* webpackChunkName: "goods" */ "../views/Goods.vue"),
  },
  {
    path: "/order",
    name: "order",
    component: () =>
      import(/* webpackChunkName: "order" */ "../views/Order.vue"),
  },
  {
    path: "/user",
    name: "user",
    component: () => import(/* webpackChunkName: "user" */ "../views/User.vue"),
    // 路由独享守卫
    // beforeEnter: (to, from, next) => {
    //   console.log("to", to, "from", from);
    //   let token = localStorage.getItem("x-auth-token");
    //   // 此时必须要有token
    //   if (token) {
    //     next(); // next()去到to所对应的路由界面
    //   } else {
    //     // 提示没有登录
    //     store.dispatch("showToast/asyncChangeIsShowToast", {
    //       msg: "你还没有登录！",
    //       type: "warning",
    //     });
    //   }
    // },
    redirect: "/user/cart",
    children: [
      {
        path: "/user/cart",
        component: () =>
          import(/* webpackChunkName: "cart" */ "../components/user/Cart.vue"),
      },
    ],
  },
  {
    path: "/free",
    name: "free",
    component: () => import(/* webpackChunkName: "free" */ "../views/Free.vue"),
  },
  {
    path: "/details",
    name: "details",
    component: () =>
      import(/* webpackChunkName: "details" */ "../views/Details.vue"),
<<<<<<< HEAD
  },
  {
    // 匹配所有地址
    path: "*",
    name: "Error",
    component: () =>
      import(/* webpackChunkName: "error" */ "../views/Error.vue"),
=======
>>>>>>> 42d7f4a3812cbaa13e12bafc11903e5f94f4bd8a
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 导航守卫
// 路由全局守卫
// 前置导航守卫有三个参数
// to  表示即将进入的路由
// from  表示即将离开的路由
// next() 表示执行进入这个路由
/* router.beforeEach((to, from, next) => {
  console.log("to", to, "from", from);
  if (to.path == "/user") {
    let token = localStorage.getItem("x-auth-token");
    // 此时必须要有token
    if (token) {
      next(); // next()去到to所对应的路由界面
    } else {
      // 提示没有登录
      store.dispatch("showToast/asyncChangeIsShowToast", {
        msg: "你还没有登录！",
        type: "warning",
      });
    }
    return; // 需要些return，防止执行完上面的next()，还继续执行下面的next()
  }
  next();
}); */

export default router;
